<template>
	<view class="page">

		<view class="wrapper" v-if="shopList.length > 0">
			<view v-for="(storeItem, storeIndex) in shopList" :key="storeItem.store_id">
				 <view class="content">
				 	<view class="title" @tap="goShop(storeItem.store_id)">
				 		<view @click.stop="selectAll(storeIndex)">
				 			<text class="iconfont icon-quan" v-if="(status == '' && storeItem.selected == false) || (status == 'edit' && !storeItem.deleted)"></text>
				 			<text class="iconfont icon-gou" :style="'color:' + mobile_head_color" v-if="(status == '' && storeItem.selected == true) || (status == 'edit' && storeItem.deleted)"></text>
				 		</view>
				 		<image :src="storeItem.image"></image>
				 		<text>{{storeItem.store_name}}</text>
				 		<text class="iconfont icon-jiantou"></text>
				 	</view>
				 
				 	<view class="goods-item" v-for="(item, index) in storeItem.goods_list" :key="index">
				 		<view class="icon-box" @click.stop="selectOne(storeIndex, index)">
				 			<text class="iconfont icon-quan" v-if="(status == '' && item.selected == false) || (status == 'edit' && item.deleted != true)"></text>
				 			<text class="iconfont icon-gou" :style="'color:' + mobile_head_color" v-if="status == '' && item.selected != false"></text>
				 			<text class="iconfont icon-gou" :style="'color:' + mobile_head_color" v-if="status == 'edit' && item.deleted == true"></text>
				 		</view>
				 		<view class="info-box" @click.stop="goShop(storeItem.store_id, item.sort_id, item.goods_id)">
				 			<image :src="item.image" mode="aspectFill"></image>
				 			<view class="info">
				 				<view class="name">{{item.name}}</view>
				 				<view class="gray-text">
				 					<text v-if="item.str">{{item.str}}</text>
				 				</view>
				 				<view class="price-box">
				 					<text class="gray-text">X{{item.num}}</text>
				 					<view>
				 						<view class="gray-text prev-price block-in" v-if="item.is_seckill_price && item.o_price">
				 							<currency></currency>{{item.o_price}}
				 						</view>
				 						<view class="now-price block-in">
				 							<currency></currency>{{item.price}}
				 						</view>
				 					</view>
				 				</view>
				 			</view>
				 		</view>
				 	</view>
				 
				 	<view class="fee" v-if="status === '' && storeItem.pack_fee > 0">
				 		<view>
				 			<lang keywords="包装费"></lang>
				 		</view>
				 		<view>
				 			<currency></currency>{{storeItem.pack_fee}}
				 		</view>
				 	</view>
				 
				 	<view class="cost-box border-t" v-if="status === ''">
				 		<view>
				 			<lang style="color:#333;font-size: 16px;margin-right:5px;" keywords="商品总价"></lang>
				 			<view class="total-price block-in">
				 				<currency></currency>{{storeItem.total_price}}
				 			</view>
				 		</view>
				 		<view>
				 			<button class="gray" v-if="storeItem.total_price == 0 && storeItem.selectNum == 0" :key="'basic_price' + storeItem.store_id">
				 				<currency></currency>{{storeItem.basic_price > 0 ? storeItem.basic_price : 0}}
				 				<lang keywords="起送" :left="true"></lang>
				 			</button>
				 			<button class="gray" v-if="storeItem.selectNum > 0 && storeItem.total_price < storeItem.basic_price" :key="'must_price' + storeItem.store_id">
				 				<lang keywords="还差X1" :X1="storeItem.deficit" unit="yuanSymbol"></lang>
				 			</button>
							<button class="gray" v-if="storeItem.selectNum > 0 && storeItem.total_price >= storeItem.basic_price && storeItem.mustBuy" @click="mustBuyClick(storeIndex)" :key="'must_food' + storeItem.store_id">
								<lang keywords="未点必选品"></lang>
							</button>
				 			<button :style="'background:' + mobile_head_color" hover-class="btn-hover" v-if="storeItem.selectNum > 0 && storeItem.total_price >= storeItem.basic_price && !storeItem.mustBuy"
				 			 @click.stop="settleAccounts(storeIndex)" :key="'go_pay' + storeItem.store_id">
				 				<lang keywords="去结算"></lang>
				 			</button>
				 		</view>
				 	</view>
				 
				 </view>
				 
				 
			</view>

			<view v-if="unoptionalList.length > 0">
				<view class="not-title border-b">
					<view class="desc">
						<lang keywords="不在配送范围商家"></lang>
					</view>
					<view class="address-box">
						<view>
							<text class="iconfont icon-dingwei1"></text>
							<text>{{address.address_name}}</text>
						</view>
						<view class="show-btn" @click.stop="showNoListHandle">
							<block v-if="showNoList">
								<lang keywords="收起"></lang>
							</block>
							<block v-else>
								<lang keywords="展开"></lang>
							</block>
							<text :class="'iconfont ' + (showNoList ? 'icon-jiantou1' : 'icon-xiala') + ' '"></text>
						</view>
					</view>
				</view>
				<view class="not-list" v-if="showNoList">
					<view v-for="(item, index) in unoptionalList" :key="index">
						<shopcart :color="mobile_head_color" tag="page" :selectGoods="item.selectGoods" :storeInfo="item.storeInfo"
						 :status="status" :listIndex="index" listName="unoptionalList" @updateList="updateList"></shopcart>
					</view>
					<view :class="' ' + (showMask ? 'mask' : '')"></view>
				</view>
			</view>

			<view class="btn-box" v-if="!status" @tap="editClick">
				<button class="edit" hover-class="edit-hover" :style="'background:' + mobile_head_color" key='editCart'>
					<lang keywords="编辑"></lang>
				</button>
			</view>

			<view class="btn-box" v-if="status">
				<button class="cancel" hover-class="cancel-hover" @tap="cancelClick" key='cancelCart'>
					<lang keywords="取消"></lang>
				</button>
				<button class="delete" :style="'background:' + mobile_head_color" hover-class="delete-hover" @tap="deleteClick" key='delCart'>
					<lang keywords="删除"></lang>
				</button>
			</view>
		</view>

		<view class="empty-wrapper" v-if="shopList.length == 0">
			<view class="empty">
				<image src="../../../static/images/sn_shopcartnull.jpg" mode="widthFix"></image>
				<view>
					<lang keywords="购物车空空如也，快去逛逛吧~"></lang>
				</view>
				<button :style="'background:' + mobile_head_color" @tap="goback" key='goIndex'>
					<lang keywords="逛一逛"></lang>
				</button>
			</view>
		</view>
		
		<userinfo :options="user_options" @getUserscope="getUserInfo" @toLogin="getUserInfo"></userinfo>
	</view>
</template>

<script>
	import common from '../../../utils/common.js'
	var app = getApp();
	var _this;

	export default {
		data() {
			return {
				showNoList: false,
				storeList: [],
				optionalList: [], // 在配送范围内或允许自提的商家
				unoptionalList: [], // 不在配送范围且不支持自提，休息中的商家
				
				address: {}, // 缓存的配送地址
				showMask: true, // 是否显示不在配送范围商家的蒙层
				status: '', // 标记是否删除状态
				mobile_head_color: '', // 主颜色
				user_options: {},
				shopList: [], // 店铺列表
				deleteTotalNum: 0, // 选中的删除的商品数量
			};
		},
		// 生命周期函数--监听页面加载
		onLoad: function() {
			_this = this;
			common.setMainColor(_this, function(config){
				
			});
			wx.setNavigationBarTitle({
				title: common.changeTxt('购物车')
			})
			console.log('2222221111', app)
			app.globalData.goodsSelect = {}
		},
		onShow() {
			var address = app.globalData.delivery_address
			if (address) {
				_this.address = address
			}
			getShopList()
			
			// #ifdef H5
			common.hideWxShare()
			// #endif
		},
		methods: {
			// 未点必选分类
			mustBuyClick (storeIndex) {
				let name = this.shopList[storeIndex].required_sort.sort_name
				uni.showToast({
					title: common.changeTxt('需要选择【X1】下的商品才可下单哦~', {X1: name}),
					icon: 'none'
				})
			},
			// 结算按钮
			settleAccounts (storIndex) {
				let arr = []
				let store_id = this.shopList[storIndex].store_id
				this.shopList[storIndex].goods_list.map(item => {
					if (item.selected) {
						arr.push(item.uniqueness_number)
					}
					return item
				})
				common.post('Cart&a=chooseProduct', {"uniqueness_number":arr, store_id:store_id, noTip:true}, function(data){
					uni.navigateTo({
						url: '/pages/shop_new/confirmOrder/newCart?store_id=' + store_id
					});
				})
			},
			// 单个选择按钮
			selectOne(storeIndex, goodsIndex) {
				var obj = app.globalData.goodsSelect ? app.globalData.goodsSelect : {}
				var str = this.status == '' ? 'selected' : 'deleted'
				this.shopList[storeIndex].goods_list[goodsIndex][str] = !this.shopList[storeIndex].goods_list[goodsIndex][str]
				let store = this.shopList[storeIndex]
				let goods = this.shopList[storeIndex].goods_list[goodsIndex]
				if (str == 'deleted') {
					if (goods.deleted) {
						store.deleteNum = store.deleteNum + 1
						_this.deleteTotalNum = _this.deleteTotalNum + 1
					} else {
						store.deleteNum = store.deleteNum - 1
						_this.deleteTotalNum = _this.deleteTotalNum - 1
					}
					store.deleted = store.deleteNum == store.goods_list.length
				} else {
					if (goods.selected) {
						store.selectNum = store.selectNum + 1
						
						if (store.pack_type == 1) {
							store.pack_fee = store.pack_fee * 1 + goods.packing_charge * 1
							store.total_price = store.total_price + (goods.packing_charge * 1 + goods.price * 1)
						} else {
							store.pack_fee = store.orderPackFee
							store.total_price = store.total_price + goods.price * 1
						}
					} else {
						store.selectNum = store.selectNum - 1
						if (store.pack_type == 1) {
							store.pack_fee = store.pack_fee * 1 - goods.packing_charge * 1
							store.total_price = store.total_price - (goods.packing_charge * 1 + goods.price * 1)
						} else {
							store.total_price = store.total_price - goods.price * 1
							if (store.selectNum == 0) {
								store.pack_fee = 0
								store.total_price = 0
							}
						}
					}
					store.deficit = store.basic_price * 1 - store.total_price * 1
					store.selected = store.selectNum == store.goods_list.length
					
					store.pack_fee = this.numberToFixed(store.pack_fee)
					store.total_price = store.total_price < 0 ? 0 : this.numberToFixed(store.total_price)
					store.deficit = this.numberToFixed(store.deficit)
					if (store.required_sort.sort_id == goods.sort_id) {
						store.mustBuy = !goods.selected
					}
				}
				this.shopList[storeIndex].goods_list[goodsIndex] = goods
				this.shopList[storeIndex] = store
				obj[goods.uniqueness_number] = {
					selected: goods.selected,
					deleted: goods.deleted
				}
				app.globalData.goodsSelect = obj
			},
			
			numberToFixed (number) {
				if(String(number).indexOf(".") != -1) {
					number = number.toFixed(2) * 1
				}
				return number
			},
			
			// 全选
			selectAll(storeIndex) {
				var obj = app.globalData.goodsSelect ? app.globalData.goodsSelect : {}
				var str = this.status === '' ? 'selected' : 'deleted'
				this.shopList[storeIndex][str] = !this.shopList[storeIndex][str]
				this.shopList = this.shopList.map((store, index) => {
					if (index == storeIndex) {
						if (str == 'deleted') {
							store.goods_list.map(goods => {
								goods.deleted = store.deleted
								obj[goods.uniqueness_number] = {
									selected: goods.selected,
									deleted: goods.deleted
								}
								return goods
							})
							store.deleteNum = store.deleted ? store.goods_list.length : 0
							_this.deleteTotalNum = store.deleted ? _this.deleteTotalNum + store.goods_list.length : _this.deleteTotalNum - store.goods_list.length
						} else {
							let total_price = 0
							// pack_type打包费类别 1商品 2店铺
							store.pack_fee = 0
							store.goods_list.map(goods => {
								goods.selected = store.selected
								if (goods.selected) {
									if (store.pack_type == 1) {
										store.pack_fee = store.pack_fee * 1 + goods.packing_charge * 1
									} else {
										store.pack_fee = store.orderPackFee
									}
									total_price = total_price + goods.price * 1
								}
								
								obj[goods.uniqueness_number] = {
									selected: goods.selected,
									deleted: goods.deleted
								}
								return goods
							})
							store.total_price = total_price + store.pack_fee * 1
							store.deficit = store.basic_price - store.total_price
							store.selectNum = store.selected ? store.goods_list.length : 0
							store.pack_fee = this.numberToFixed(store.pack_fee)
							store.total_price = store.total_price < 0 ? 0 : this.numberToFixed(store.total_price)
							store.deficit = this.numberToFixed(store.deficit)
							if (store.required_sort.sort_id) {
								store.mustBuy = !store.selected
							}
						}
					}
					return store
				})
				app.globalData.goodsSelect = obj
			},
			
			goShop(store_id, sort_id, goods_id) {
				var url = '/pages/shop_new/shopDetail/shopDetail?store_id=' + store_id;
				if(sort_id && goods_id){
					url = url + '&sort_id=' + sort_id + '&goods_id=' + goods_id;
				}
				wx.navigateTo({
					url: url
				});
			},
			getUserInfo (e) {
				
			},
			// 购物车空时，逛一逛按钮
			goback() {
				common.navigateBack()
			},

			// 显示不在配送范围的商家
			showNoListHandle() {
				_this.showNoList = !_this.showNoList
			},

			// 编辑
			editClick() {
				_this.status = 'edit'
				_this.showMask = false
			},

			// 取消
			cancelClick() {
				_this.status = ''
				_this.showMask = true
			},

			// 删除
			deleteClick(e) {
				// 判断是否有删除的商品
				console.log('删除的商品数量', 	_this.deleteTotalNum)
				if (!_this.deleteTotalNum) {
					wx.showToast({
						title: common.changeTxt('请选择需要删除的商品！'),
						icon: 'none'
					});
					return
				}
				wx.showModal({
					title: common.changeTxt('提示'),
					content: common.changeTxt('确认删除吗？'),
					success: res => {
						if (res.confirm) {
							let arr = []
							_this.shopList.map(store => {
								store.goods_list.map(goods => {
									if (goods.deleted) {
										arr.push(goods.uniqueness_number)
									}
									return goods
								})
								return store
							})
							common.post('Cart&a=deleteProduct', {"uniqueness_number": arr}, function(data){
								console.log('删除成功', data)
								let obj = app.globalData.goodsSelect
								arr.map(item => {
									delete obj[item]
									return item
								})
								app.globalData.goodsSelect = obj
								getShopList()
								uni.showToast({
									title: common.changeTxt('删除成功')
								})
							}, _this, function(err){
								console.log('删除失败', err)
								uni.showToast({
									title: common.changeTxt('删除失败, 请重试'),
									icon: 'none'
								})
							})
						}
					}
				});
			
			},
		}
	};
	
	const getShopList = () => {
		if (!app.globalData.is_login) {
			_this.user_options = {
				toLogin: true,
				showWebMask: true
			}
			return
		}
		let param = {}
		if (_this.address.lng) {
			param.lng = _this.address.lng
			param.lat = _this.address.lat
		}
		common.post('Cart&a=allStore', param, function(data){
			let deleteTotalNum = 0
			data = data.map(store => {
				let total_price = 0
				let selectNum = 0
				let deleteNum = 0
				let mustBuy = true
				// pack_type打包费类别 1商品 2店铺
				if (store.pack_type == 2) {
					store.orderPackFee = store.pack_fee
				}
				store.pack_fee = 0
			    store.goods_list.map(goods => {
					if (app.globalData.goodsSelect && app.globalData.goodsSelect[goods.uniqueness_number]) {
						if (app.globalData.goodsSelect[goods.uniqueness_number].deleted === false) {
							goods.deleted = false
						} else {
							deleteNum++
							goods.deleted = true
						}
						if (app.globalData.goodsSelect[goods.uniqueness_number].selected === false) {
							goods.selected = false
						} else {
							selectNum++
							goods.selected = true
						}
					} else {
						deleteNum++
						selectNum++
						goods.deleted = true
						goods.selected = true
					}
					if (goods.selected) {
						if (store.pack_type == 1) {
							store.pack_fee = store.pack_fee*1 + goods.packing_charge*goods.num
						} else {
							store.pack_fee = store.orderPackFee
						}
						total_price = total_price*1 + goods.price*1
						if (store.required_sort.sort_id == goods.sort_id) {
							mustBuy = false
						}
					}
					return goods
					
				})
				store.total_price = _this.numberToFixed(total_price*1 + store.pack_fee*1); 
				store.deficit = store.basic_price - store.total_price
				store.selectNum = selectNum
				store.deleteNum = deleteNum
				store.selected = selectNum == store.goods_list.length
				store.deleted = deleteNum == store.goods_list.length
				if (store.required_sort.sort_id) {
					console.log('请求购物车数据，2222222222')
					store.mustBuy = mustBuy
				} else {
					store.mustBuy = false
				}1
				
				deleteTotalNum = deleteTotalNum + deleteNum
				return store
			}) 
			console.log('购物车数据', data)
			_this.shopList = data
			_this.deleteTotalNum = deleteTotalNum
		})
	}
</script>
<style>	
	.border-t,
	.border-b {
		position: relative;
	}

	.border-t::after {
		content: '';
		position: absolute;
		top: 0;
		left: 10px;
		height: 1rpx;
		width: 100%;
		background: #e5e5e5;
		transform: scaleY(0.5);
	}

	.border-b::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 10px;
		height: 1rpx;
		width: 100%;
		background: #e5e5e5;
		transform: scaleY(0.5);
	}

	.page {
		width: 100%;
		height: 100%;
		position: relative;
		overflow-x: hidden;
	}

	.wrapper {
		padding-bottom: 50px;
		width: 100%;
		overflow-x: hidden;
	}

	.not-title {
		background: #fff;
		padding: 10px;
	}

	.not-title .desc {
		font-size: 16px;
		color: #333;
	}

	.not-title .address-box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		color: #999;
		font-size: 14px;
	}

	.not-title .show-btn {
		border: 1rpx solid #e5e5e5;
		padding: 5px 10px;
		border-radius: 20px;
		color: #333;
	}

	.not-list {
		position: relative;
	}

	.not-list .mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, .5)
	}

	.btn-box {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
	}

	.btn-box button {
		background: #fb4e44;
		border-radius: 0;
		color: #fff;
		font-size: 16px;
		height: 50px;
		line-height: 50px;
	}

	.btn-box .edit {
		background: #06c1ae;
		flex: 1;
	}

	.btn-box .edit-hover {
		background: #04ad9c
	}

	.btn-box .cancel {
		background: #ccc;
		flex: 1;
	}

	.btn-box .cancel-hover {
		background: rgb(187, 182, 182);
	}

	.btn-box .delete {
		flex: 3;
	}

	.btn-box .delete-hover {
		background: #ec453c;
	}

	.empty-wrapper {
		width: 100%;
		height: 100vh;
		background: #fff;
	}

	.empty {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		font-size: 14px;
		color: #999;
		text-align: center;
	}

	.empty image {
		width: 200px;
		height: 200px;
	}

	.empty button {
		font-size: 14px;
		display: inline-block;
		margin-top: 20px;
		padding: 0 20px;
		color: #fff;
	}
	
	/* 购物车页面样式 */
	.content {
		background: #fff;
		margin-bottom: 10px;
	}
	
	.content .title {
		padding: 10px;
		height: 30px;
		line-height: 30px;
		display: flex;
		align-items: center;
		font-size: 16px;
		color: #333;
	}
	
	.content .title image {
		width: 30px;
		height: 30px;
		margin-right: 5px;
	}
	
	.content .title .icon-jiantou {
		font-size: 20px;
		color: #999;
	}
	
	.content .line {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		font-size: 12px;
		color: #666;
		padding: 0 10px 10px 44px;
	}
	
	.content .line text {
		white-space: nowrap;
	}
	
	.content .line .tag {
		border-radius: 2px;
		margin-right: 5px;
		padding: 0 2px;
	}
	
	.content .line .sale {
		color: #cb7a75;
		border: 1rpx solid #cb7a75;
		background: #fff4f2;
	}
	
	.content .line .text-overflow {
		white-space: nowrap;
		text-overflow: ellipsis;
		overflow: hidden;
		display: inline-block;
	}
	
	.content .goods-item {
		display: flex;
		padding: 0 0 10px 10px;
		width: 100%;
		box-sizing: border-box;
		align-items: center;
	}
	
	.content .goods-item .info-box {
		min-height: 75px;
		display: flex;
		background: #f8f8f8;
		width: calc(100% - 34px);
	}
	
	.content .goods-item .info-box image {
		height: 75px;
		width: 75px;
		display: block;
		flex-shrink: 0;
	}
	
	.content .goods-item .info-box .info {
		padding: 8px 10px;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		width: calc(100% - 75px);
		box-sizing: border-box;
	}
	
	.content .goods-item .info-box .info .name {
		font-size: 14px;
		font-weight: bold;
		color: #333;
		margin-bottom: 3px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
	
	.content .goods-item .info-box .info .gray-text {
		font-size: 12px;
		color: #999;
	}
	
	.content .goods-item .info-box .info .price-box {
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
	}
	
	.content .goods-item .info-box .info .price-box .prev-price {
		text-decoration: line-through;
		margin-right: 5px;
	}
	
	.content .goods-item .info-box .info .price-box .now-price {
		font-size: 14px;
		color: #333;
	}
	
	.content .goods-item .add-pricce {
		display: flex;
		justify-content: space-between;
		width: 100%;
		padding-right: 10px;
		font-size: 14px;
		color: #333;
	}
	
	.content .fee {
		padding: 0 10px 10px 44px;
		display: flex;
		justify-content: space-between;
		font-size: 14px;
		color: #333;
	}
	
	.content .cost-box {
		padding: 10px 10px 10px 44px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.content .cost-box .discount {
		font-size: 16px;
		color: #333;
	}
	
	.content .cost-box .total-price {
		font-size: 16px;
		color: #fb4e44;
		font-weight: bold;
		margin-right: 10px;
	}
	
	.content .cost-box button {
		display: inline;
		padding: 10px 20px;
		background: #06c1ae;
		color: #fff;
		border-radius: 0;
		font-size: 16px;
	}
	
	.content button::after {
		border: none;
	}
	
	.content .cost-box .btn-hover {
		background: #03ac9b
	}
	
	.content .iconfont {
		color: #e5e5e5;
		font-size: 24px;
		margin-right: 10px;
	}
	
	.content button.gray {
		background: #e5e5e5;
		color: #666;
	}
</style>
